const requesturl="43.136.220.136:5000"  // 动态后端请求
const requesturlfront="43.136.220.136" // 静态资源加载
new Vue({
    el: '#appzhutiye', // 指定Vue根实例的挂载点
    data: {
        Menutopic:null,
        draggedCard:null,
        draggedType:'',
        currentFolder:null,
        currentCards:[],
        breadcrumbList: [],
        draggedTopic:null,
    message: 'Hello World from Vue.js!', // 动态数据
    token:"",
    uid:"",
    count: 0, // 另一个动态数据
    topictitle:'测试',
    searchQuery: '', // 新增的搜索框绑定数据
    topiczu: [

    ],
    showRenameDialog: false,
    newName: '',
    itemToRename: null,
    newTopicName: '',


},
    computed: {
    // 计算属性用于过滤列表
    filteredTopics() {
    if (!this.searchQuery.trim()) {
    return this.topiczu;
}
    return this.topiczu.filter(item => item.topictitle.includes(this.searchQuery));
}
},
    methods: {
        clickMenu(topic){
            Menutopic = topic
            this.Menutopic = topic
        },
        handleBreadcrumbDrop(event, targetCrumb) {
            event.preventDefault();
            if(this.draggedType==='card'){

                const topicId = event.target.getAttribute('foldId');
                //    找到localstorage中的名为cards的对象中对应字典key为 localstorage中 dangqianzhuti的值的previewcards对象，将previewcards中的和this.draggedCard的id相等的元素进行剔除并找到
                this.draggedFromCardToFold(event,topicId,event.target.textContent);
                this.fetchCardsFromLocalStorage( this.currentFolder.topictitle);
            }else{

                const topic = this.draggedTopic;
                console.log("🚀 ~ file: car dzhuye-vue.js ~ line 36 ~ topic: ",topic);
                const topicId = event.target.getAttribute('foldId');
                console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 37 ~ topicId: ",topicId);
                // const draggedTopicId = event.dataTransfer.getData("text/plain");
                this.moveTopicToBreadcrumb(topic.topicid,topicId);

            }
        },
        moveTopicToBreadcrumb(draggedTopicId, targetTopicId) {
            let draggedTopic = null;

            // 定义一个递归函数来遍历并尝试移除topic
            function removeTopicRecursive(topicList, id) {
                for (let i = 0; i < topicList.length; i++) {
                    if (topicList[i].topicid === id) {
                        // 找到对应的topic，从数组中移除并返回该topic
                        draggedTopic = topicList.splice(i, 1)[0];
                        return true; // 返回true表示找到并移除了topic
                    }
                    // 如果当前topic有children，递归检查children
                    if (topicList[i].children && topicList[i].children.length > 0) {
                        if (removeTopicRecursive(topicList[i].children, id)) {
                            return true; // 在children中找到并移除了topic
                        }
                    }
                }
                return false; // 没有找到对应的topic
            }

            // 定义一个递归函数来找到目标topic，并将被拖拽的topic插入到其children中
            function insertTopicRecursive(topicList, targetId, topicToInsert) {
                for (let topic of topicList) {
                    if (topic.topicid === targetId) {
                        // 找到目标topic，将被拖拽的topic插入到其children中
                        if (!topic.children) {
                            topic.children = []; // 确保children数组存在
                        }
                        topic.children.push(topicToInsert);
                        return true;
                    }
                    // 递归搜索children
                    if (topic.children && topic.children.length > 0) {
                        if (insertTopicRecursive(topic.children, targetId, topicToInsert)) {
                            return true;
                        }
                    }
                }
                return false;
            }

            // 从当前主题列表移除被拖拽的topic
            removeTopicRecursive(this.breadcrumbList, draggedTopicId);

            console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 87 ~ draggedTopic: ",draggedTopic);
            // 如果被拖拽的topic成功移除，尝试将其插入到目标位置
            if (draggedTopic) {
                const ifInsert = insertTopicRecursive(this.breadcrumbList, targetTopicId, draggedTopic);
                // todo localstorage.set
                this.saveTopicsToLocalStorage();
                localStorage.setItem('maxEditTimeZhuti', 0);
                console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 91 ~ ifInsert: ",ifInsert);
                console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 92 ~ this.breadcrumbList.length: ",this.breadcrumbList.length);
                console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 93 ~ this.breadcrumbList: ",this.breadcrumbList);

            }
        },

        handleDrop(crumb, event) {
            event.preventDefault();
            // 获取被拖拽文件夹的ID
            const folderId = event.dataTransfer.getData("text/plain");
            // 根据ID和目标面包屑执行移动逻辑
            this.moveFolderTo(folderId, crumb.id);
        },
    removeFromBreadcrumb(topicId) {
    // 定义一个递归函数来遍历并尝试移除topic
    function removeTopicRecursive(topicList, id) {
        for (let i = 0; i < topicList.length; i++) {
            if (topicList[i].topicid === id) {
                // 找到对应的topic，从数组中移除
                topicList.splice(i, 1);
                return true; // 返回true表示找到并移除了topic
            }
            // 如果当前topic有children，递归检查children
            if (topicList[i].children && topicList[i].children.length > 0) {
                if (removeTopicRecursive(topicList[i].children, id)) {
                    return true; // 在children中找到并移除了topic
                }
            }
        }
        return false; // 没有找到对应的topic
    }

    // 从breadcrumbList的每个层级尝试移除topic
    removeTopicRecursive(this.breadcrumbList, topicId);
},
       removeBreadcrumbTopic(removeTopicId) {
    // 寻找要删除的topic在breadcrumbList中的索引
    const index = this.breadcrumbList.findIndex(topic => topic.topicid === removeTopicId);

    // 如果找到了，从breadcrumbList中移除
    if (index !== -1) {
        this.breadcrumbList.splice(index, 1);
    }

    // 此处应有代码以适当方式更新组件状态或重新渲染
},
        // 从localStorage读取zhuti数据
        fetchZhutiFromLocalStorage() {
            const zhutiData = localStorage.getItem('zhuti');
            if (zhutiData) {
                return JSON.parse(zhutiData);
            }
            return null; // 或返回默认值
        },
        resetToRoot() {

            // 假设 topiczu 是根目录的数据
            // 如果根目录有特定的数据结构，请调整此逻辑
            if(this.breadcrumbList.length==0){
                this.fetchAndStoreZhuti1().then(() => {
                    this.pageInit();
                    this.reloadWebflowJs(); // 重新加载 webflow.js
                });
            }

        },
        fetchCardsFromLocalStorage(topicName) {
            // 从localStorage获取cards数据
            const cardsData = JSON.parse(localStorage.getItem('cards') || '{}');
            // 检索与主题名称匹配的卡片列表
            const cards = cardsData[topicName] ? cardsData[topicName].previewCards : [];
            // 更新currentCards属性以反映新的卡片列表
            this.currentCards = cards;
        },
        navigateToFolder(index) {
          console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 85 ~ index: ",index);
            // 导航到选中的面包屑索引位置
            this.breadcrumbList = this.breadcrumbList.slice(0, index + 1);
            this.currentFolder = this.breadcrumbList[index];
            this.topiczu = this.currentFolder.children || [];
            this.reloadWebflowJs(); // 重新加载 webflow.js

            localStorage.setItem('dangqianzhuti', this.currentFolder.topictitle);
            this.fetchCardsFromLocalStorage( this.currentFolder.topictitle);

        },
    childrenTopic(topic){
        this.currentFolder = topic;
        // 更新面包屑导航数据
        this.breadcrumbList.push(topic);
        // 更新页面中展示的 topic 数据为当前文件夹的子节点
        this.topiczu = topic.children || [];
        this.reloadWebflowJs(); // 重新加载 webflow.js
        localStorage.setItem('dangqianzhuti', topic.topictitle);
        this.fetchCardsFromLocalStorage(topic.topictitle);
    },
        draggedFromCardToFold: function (event,topicId,breadTitle) {
            // Retrieve the current theme from localStorage
            const currentThemeId = localStorage.getItem('dangqianzhuti');
            // Assuming cards are stored in an array under each theme's 'previewCards' key in localStorage
            const themes = JSON.parse(localStorage.getItem('cards')) || {};
            const currentTheme = themes[currentThemeId];


            const targetTopicIndex = this.topiczu.findIndex(topic => topic.topicid === topicId);
            var targetTopicTitle = ""
            if(targetTopicIndex===-1){
                //没有拖放到正确位置
                if(breadTitle===''){
                    return ;
                }
                targetTopicTitle = breadTitle
            }else{
                targetTopicTitle = this.topiczu[targetTopicIndex].topictitle
            }
            const currentThemeDragTo = themes[targetTopicTitle];
            if (!currentThemeDragTo) {
                themes[targetTopicTitle] = {'order': '', 'previewCards': []}
            }
            // todo 修改这个cards的时间,添加到toes列表
            this.draggedCard.updatetime = new Date().toISOString().slice(0, 19).replace('T', ' ')
            themes[targetTopicTitle].previewCards.unshift(this.draggedCard)
            console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 222 ~ themes: ",themes);



            if (currentTheme && currentTheme.previewCards) {
                // Filter out the card that matches this.draggedCard's ID
                const updatedPreviewCards = currentTheme.previewCards.filter(card => card.id !== this.draggedCard.id);

                // Update the theme with the new list of previewCards
                currentTheme.previewCards = updatedPreviewCards;
                themes[currentThemeId] = currentTheme;
                // Update localStorage
            }







            localStorage.setItem('cards', JSON.stringify(themes));
        },
        dropTopic(event) {


        event.preventDefault();

        if(this.draggedType==='card'){
            const topicId = event.target.getAttribute('id');
        //    找到localstorage中的名为cards的对象中对应字典key为 localstorage中 dangqianzhuti的值的previewcards对象，将previewcards中的和this.draggedCard的id相等的元素进行剔除并找到
            this.draggedFromCardToFold(event,topicId,'');

        }else{

            const topic = this.draggedTopic;
            console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 60 ~ topic: ",topic);
            const topicId = event.target.getAttribute('id');
            console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 36 ~ event.target: ",event.target);
            console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 59 ~ topicId: ",topicId);
              // 在 topiczu 中查找对应的 topicId
              const targetTopicIndex = this.topiczu.findIndex(topic => topic.topicid === topicId);
              console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 40 ~ targetTopicIndex: ",targetTopicIndex);

              if (targetTopicIndex !== -1 && topicId!==topic.topicid) {
                const targetTopic = this.topiczu[targetTopicIndex];
                // 将 draggedTopic 作为 targetTopic 的子节点放入其中
                if (!targetTopic.children) {
                  // 如果目标 topic 还没有 children 属性，则创建一个空数组
                  targetTopic.children = [];
                }
                // 将 draggedTopic 添加到 targetTopic 的 children 数组中
                targetTopic.children.unshift(this.draggedTopic);

                // 更新修改后的 targetTopic 到 this.topiczu 中
                this.$set(this.topiczu, targetTopicIndex, targetTopic);

                // 从 this.topiczu 中移除拖拽的 topic
                const draggedTopicIndex = this.topiczu.findIndex(topic => topic.topicid === this.draggedTopic.topicid);
                if (draggedTopicIndex !== -1) {
                  this.topiczu.splice(draggedTopicIndex, 1);
                }
                // 在这里可以进一步处理将 draggedTopic 放入 targetTopic 的逻辑
                console.log(`Dropped topic: ${this.draggedTopic} into topic with ID: ${topicId}`);
                this.saveTopicsToLocalStorage();
                //这种没有时间状态的保存
                localStorage.setItem('maxEditTimeZhuti', 0);

              } else {
                console.log(`Failed to find topic with ID: ${topicId}`);
              }
            console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 61 ~ this.topiczu: ",this.topiczu);
            // 执行将拖拽的数据放到下一级目录中的逻辑,拖拽到下一级目录
        }
        this.fetchCardsFromLocalStorage( this.currentFolder.topictitle);
    },
    dragStart(event, item,type) {
        this.draggedType = type;
        console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 31 ~ item: ",item);
        // 将拖拽的数据传递给拖拽目标
        // 拖拽目标数据打印，打印拖拽目标上的item内容
        console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 33 ~ dragStart ~ event: ",event);
        if (type === 'card') {
            this.draggedCard = item;
        } else {
            this.draggedTopic = item; // Assuming 'draggedTopic' is used for folders
        }

    },
    saveTopicsToLocalStorage() {
    // 创建一个新的 JSON 对象
    let json = {
    topics: this.breadcrumbList[0].children,
    order: this.breadcrumbList[0].children.map(topic => topic.topicid).join(',')
};
    // 将 JSON 对象转换为字符串并保存到 localStorage
    localStorage.setItem('zhuti', JSON.stringify(json));
},
    showAlert() {
    alert('Hello from Vue.js!');
},
    incrementCount() {
    this.count++;
},
removeTopic(topic) {
    // 更新topics数组
    this.topiczu = this.topiczu.filter(item => item.topictitle !== topic.topictitle);
    this.removeFromBreadcrumb(topic.topicid)
    this.saveTopicsToLocalStorage();

    // 直接从localStorage中获取必要的数据
    const localZhuti = JSON.parse(localStorage.getItem('zhuti')) || { "topics": [] };
    const uid = localStorage.getItem('uid');

    // 不能删除，还是重置为0，检测到为0就会重新保存
    localStorage.setItem('maxEditTimeZhuti', 0);

    // 如果topics数组为空，则提交覆盖远程数据
    if (localZhuti.topics.length === 0 && uid) {
        const data = {
            id: uid,
            zhuti: JSON.stringify(localZhuti) // 确保提交的是字符串格式的JSON
        };

        axios.post(`http://${requesturl}/proxy-user-order-cud`, data).then(response => {
            console.log('Data successfully saved to Elasticsearch', response.data);
            // 更新maxEditTimeZhuti等逻辑（如果有的话）
        }).catch(error => {
            console.error('Failed to save data to Elasticsearch', error);
        });
    }
}
,
        openRenameDialog(item) {
    this.showRenameDialog = true;
    this.newName = item.topictitle;
    this.itemToRename = item;
},
    cancelRename() {
    this.showRenameDialog = false;
    this.newName = '';
    this.itemToRename = null;
},
    renameTopic() {
    // 检查新名称是否已存在
    if (this.topiczu.some(item => item.topictitle === this.newName)) {
    alert('This name already exists.');
    return;
}
    // 检查是否有选中的项目进行重命名
    if (this.itemToRename) {
    // 获取当前日期和时间
    const now = new Date();
    const datetime = new Date().toISOString().slice(0, 19).replace('T', ' ');
    // 更新 topictitle 和 edittime
    this.itemToRename.topictitle = this.newName;
    this.itemToRename.edittime = datetime;
}
    // 关闭重命名对话框并重置相关数据
    this.cancelRename();
    this.saveTopicsToLocalStorage()
},
    addNewTopic1() {
    // 检查newTopicName是否为空
    if (!this.newTopicName.trim()) {
    alert('请输入主题名称。');
    return;
}
    // 检查主题名称是否已存在
    if (this.topiczu.some(item => item.topictitle === this.newTopicName)) {
    alert('此名称已存在。');
    return;
}
    // 获取当前日期和时间
    const now = new Date();
    const datetime = now.toISOString().slice(0, 19).replace('T', ' ');
    // 生成唯一的 topicid
    const topicid = this.uid + Date.now().toString();
    // 添加新主题
    this.topiczu.unshift({
    topicid: topicid,
    topictitle: this.newTopicName,
    edittime: datetime,
    createtime: datetime,
    topicname: this.newTopicName
});
    //同时添加到面包导航对应位置中

    // 重置输入框并关闭弹窗
    alert('添加成功');
    this.newTopicName = '';
    this.saveTopicsToLocalStorage();
//    重新渲染webflow动态效果
    this.reloadWebflowJs()

},
        addNewTopic() {
            if (!this.newTopicName.trim()) {
                alert('请输入主题名称。');
                return;
            }
            if (this.topiczu.some(item => item.topictitle === this.newTopicName)) {
                alert('此名称已存在。');
                return;
            }
            const now = new Date();
            const datetime = now.toISOString().slice(0, 19).replace('T', ' ');
            const topicid = this.uid + Date.now().toString();
            const newTopic = {
                topicid: topicid,
                topictitle: this.newTopicName,
                edittime: datetime,
                createtime: datetime,
                topicname: this.newTopicName,
                children: []
            };

            console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 276 ~ this.currentFolder: ",this.currentFolder);
            // 判断当前是否有选中的父文件夹
            if (this.currentFolder) {
                // 如果有，将新主题添加到该文件夹的子主题中
                if (!this.currentFolder.children) {
                    this.currentFolder.children = [];
                }
                this.currentFolder.children.push(newTopic);
            } else {
                this.topiczu.unshift(newTopic);
            }
// 如果没有，添加到根目录

            this.newTopicName = ''; // 重置输入框
            this.saveTopicsToLocalStorage(); // 保存更改到本地存储
            localStorage.setItem('maxEditTimeZhuti', '0');
            this.reloadWebflowJs(); // 重新渲染webflow动态效果
        },
        goToCardPerform(value) {
    // 将值保存到 localStorage
    localStorage.setItem('dangqianzhuti', value.topicname);
    localStorage.setItem('dangqianzhutititle', value.topictitle);
    // 跳转到 cardperform 页面
    window.location.href = '/cardperform';
}//
    ,
    sortByCreateTime() {
    // 按创建时间升序排序
    this.topiczu.sort((a, b) => {
    return new Date(b.createtime) - new Date(a.createtime);
});
},
    sortByEditTime() {
    // 按修改时间升序排序
    this.topiczu.sort((a, b) => {
    return new Date(b.edittime) - new Date(a.edittime);
});
},
    sortByOrderFromLocalStorage() {
    // 从 localStorage 中获取 zhuti 数据
    const zhutiData = localStorage.getItem('zhuti');
    if (zhutiData) {
    try {
    const parsedData = JSON.parse(zhutiData);
    if (parsedData && parsedData.order) {
    // 获取 order 中的 topicid 顺序
    const order = parsedData.order.split(',');
    // 根据 order 数组的顺序重排 topiczu
    this.topiczu.sort((a, b) => {
    return order.indexOf(a.topicid) - order.indexOf(b.topicid);
});
}
} catch (e) {
    console.error('Error parsing zhuti from localStorage:', e);
    // 错误处理逻辑
}
}
},
    fetchAndStoreZhuti1() {
        return new Promise((resolve, reject) => {
            const query = {
                query: {
                    bool: {
                        must: [{match: {id: localStorage.getItem('uid')}}]
                    }
                }, size: 100
            };

            axios.post('http://'+requesturl+'/proxy-user-order-r', query)
                .then(async response => {
                    let maxEditTimeLocalZhuti = 0;
                    if (response.data.hits.hits.length > 0) {
                        const zhutiData = JSON.parse(response.data.hits.hits[0]._source.zhuti);
                        console.log("zhutiData: ", zhutiData);

                        const maxEditTimeZhutiData = Math.max(...zhutiData.topics.map(topic => new Date(topic.edittime).getTime()));

                        const localZhuti = JSON.parse(localStorage.getItem('zhuti')) || {"topics": []};
                        maxEditTimeLocalZhuti = localZhuti.topics.length > 0
                            ? Math.max(...localZhuti.topics.map(topic => new Date(topic.edittime).getTime()))
                            : 0;

                        if (maxEditTimeZhutiData > maxEditTimeLocalZhuti) {
                            localStorage.setItem('zhuti', JSON.stringify(zhutiData));
                        }
                        //将maxEditTimeZhutiData保存到localStorage中，以便下次比较
                        localStorage.setItem('maxEditTimeZhuti', maxEditTimeZhutiData);
                        resolve(); // 成功解决Promise
                    } else {
                        localStorage.setItem('maxEditTimeZhuti', maxEditTimeLocalZhuti);
                        console.log('未找到匹配的数据');
                        resolve(); // 未找到数据也视为解决Promise
                    }
                })
                .catch(error => {
                    console.error('查询失败:', error);
                    reject(error); // 发生错误时拒绝Promise
                });


        });
    },
    pageInit(){
        const uid = localStorage.getItem('uid');
        if (uid) {this.uid=uid} else { alert("请登录")}
        // 触发自定义排序
        this.sortByOrderFromLocalStorage()
        // 尝试从 localStorage 中获取 zhuti 键的值
        const zhutiData = localStorage.getItem('zhuti');
        // 检查是否存在 zhuti 数据
        if (zhutiData) {
            try {
                // 解析存储的 JSON 字符串
                const parsedData = JSON.parse(zhutiData);
                // 检查解析出的数据是否包含 topics 键
                if (parsedData && parsedData.topics) {
                    // 将 topics 键的值赋给 topiczu
                    this.topiczu = parsedData.topics;
                                    }
            } catch (e) {
                console.error('Error parsing zhuti from localStorage:', e);
                // 处理错误，例如提供默认值或显示错误消息
            }
        }
        //当初始化为空时
        const virtualRootNode = {
            topicid: "00000000000", // 特殊的ID或标识符
            topictitle: "所有主题", // 显示的名称
            children: this.topiczu, // 包含所有顶级节点
        };
        this.breadcrumbList = [virtualRootNode];
},
   reloadWebflowJs() {
    // 使用querySelector直接查找含有webflow.js的<script>标签
    var script = document.querySelector('script[src*="webflow.js"]');
    if (script) {
        script.parentNode.removeChild(script);
    }

    // 创建新的<script>标签并设置src属性，包含时间戳防止缓存
    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    newScript.src = 'http://'+requesturlfront+'/js/webflow.js' + '?v=' + new Date().getTime();
    newScript.onload = function() {
        console.log('Webflow JS has been reloaded.');

        // 确保Webflow对象存在，然后重新初始化交互效果
        if (typeof Webflow !== 'undefined' && Webflow.require('ix2').init) {
            Webflow.require('ix2').init();
        }
    };
    document.head.appendChild(newScript);
},
        async fetchData1() {
            return new Promise((resolve, reject) => {
                try {
                    const query = {
                        query: {
                            bool: {
                                must: [{match: {uid: localStorage.getItem('uid')}}]
                            }
                        },
                        size: 100
                    };

                    axios.post('http://'+requesturl+'/proxy-search', query)
                        .then(async response => {
                            console.log("Response: ", response);

                            const cards = {};
                            response.data.hits.hits.forEach(hit => {
                                const cardData = hit._source;
                                const key = cardData.front.split('：')[0];
                                const front = cardData.front.split('：')[1];
                                if (!cards[key]) cards[key] = {order: "", previewCards: []};
                                cardData.front = front;
                                cardData.back = cardData.back;
                                cardData.mark = cardData.known;
                                delete cardData.known;
                                cardData.id = cardData.sqlId;
                                delete cardData.sqlId;
                                cardData.time = cardData.createtime;
                                delete cardData.createtime;
                                cardData.updatetime = cardData.lastmodifieddate;
                                delete cardData.lastmodifieddate;
                                delete cardData.uid;
                                delete cardData.type;
                                cards[key].previewCards.push(cardData);
                            });

                            const cardsLocal = JSON.parse(localStorage.getItem('cards')) || {};
                            Object.keys(cards).forEach(key => {
                                if (!cardsLocal[key]) {
                                    cardsLocal[key] = cards[key];
                                } else {
                                    cards[key].previewCards.forEach(card => {
                                        const localCardIndex = cardsLocal[key].previewCards.findIndex(localCard => localCard.id === card.id);
                                        if (localCardIndex !== -1) {
                                            if (new Date(cardsLocal[key].previewCards[localCardIndex].updatetime) < new Date(card.updatetime)) {
                                                cardsLocal[key].previewCards[localCardIndex] = card;
                                            }
                                        } else {
                                            cardsLocal[key].previewCards.push(card);
                                        }
                                    });
                                }
                            });

                            localStorage.setItem('cards', JSON.stringify(cardsLocal));
                            console.log("Updated cards: ", cardsLocal);
                            await this.updateCardsOrderFromZhuti();

                            resolve(); // 成功解决 Promise
                        })
                        .catch(error => {
                            console.error('查询失败:', error);
                            reject(error); // 在错误情况下拒绝 Promise
                        });
                } catch (error) {
                    console.error('异常错误:', error);
                    reject(error); // 捕获到异常时拒绝 Promise
                }
            });
        },
        updateCardsOrderFromZhuti() {
            return new Promise((resolve, reject) => {
                try {
                    const zhutiStorage = localStorage.getItem('zhuti');
                    const dangqianzhuti = localStorage.getItem('dangqianzhuti');
                    let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};
                    if (zhutiStorage && dangqianzhuti) {
                        const zhuti = JSON.parse(zhutiStorage);
                        if (zhuti && zhuti.topics) {
                            zhuti.topics.forEach(topic => {
                                if (topic.topictitle === dangqianzhuti) {
                                    // 确保cards中有对应的键
                                    if (!cards[dangqianzhuti]) {
                                        cards[dangqianzhuti] = {};
                                    }
                                    cards[dangqianzhuti].order = topic.order;
                                }
                            });
                        }

                        localStorage.setItem('cards', JSON.stringify(cards));
                    }

                    resolve(); // 解决 Promise
                } catch (error) {
                    console.error('Error:', error);
                    reject(error); // 捕获到异常时拒绝 Promise
                }
            });
        },
},
    // watch: {
    //     // 监听breadcrumbList的变化
    //     breadcrumbList(newValue) {
    //         if (newValue && newValue.length > 0) {
    //             // 如果breadcrumbList不为空，则获取第一个元素的children
    //             const childrenToSave = newValue[0].children;
    //             // 序列化children并保存到localStorage
    //             localStorage.setItem('zhuti', JSON.stringify(childrenToSave));
    //         }
    //     },
    // },
mounted() {
    var self = this
    const uid = localStorage.getItem('uid');
    if (uid) {
        this.uid = uid
    } else {
        alert("请登录")
    }

    this.fetchData1().then(() => {
        this.fetchAndStoreZhuti1().then(() => {
            this.pageInit()
        })
        this.pageInit()
    })

}
});


    function saveZhutiToElasticsearch() {
        const zhuti = localStorage.getItem('zhuti');
        const uid = localStorage.getItem('uid');

        const localZhuti = JSON.parse(localStorage.getItem('zhuti')) || {"topics": []};
        var maxEditTimeLocalZhuti = localZhuti.topics.length > 0
            ? Math.max(...localZhuti.topics.map(topic => new Date(topic.edittime).getTime()))
            : 0;
        console.log("🚀 ~ 2file: cardzhuye-vue0307.js ~ line 259 ~ maxEditTimeLocalZhuti: ",maxEditTimeLocalZhuti);
        //获取maxEditTimeZhuti并和maxEditTimeLocalZhuti进行比较，如果maxEditTimeZhuti大于maxEditTimeLocalZhuti，则说明有新的数据需要同步到Elasticsearch
        const maxEditTimeZhuti = localStorage.getItem('maxEditTimeZhuti') || 0;
        console.log("🚀 ~ file: cardzhuye-vue0307.js ~ line 261 ~ maxEditTimeZhuti: ",maxEditTimeZhuti);
        if (maxEditTimeZhuti < maxEditTimeLocalZhuti) {

            if (zhuti && uid) {
                const data = {
                    id: uid,
                    zhuti: zhuti
                };

                axios.post('http://'+requesturl+'/proxy-user-order-cud', data).then(response => {
                    console.log('Data successfully saved to Elasticsearch', response.data);
                    //更新maxEditTimeZhuti
                    localStorage.setItem('maxEditTimeZhuti', maxEditTimeLocalZhuti);
                }).catch(error => {
                    console.error('Failed to save data to Elasticsearch', error);
                });

            }
        } else {
            console.log("no new zhuti data to save")
        }
    }

    // 设置定时任务，每5分钟执行一次
    setInterval(saveZhutiToElasticsearch, 20000);

document.getElementById('syncButton').addEventListener('click', function() {
    saveZhutiToElasticsearch();
});
// 你可以使用beforeunload事件来监控页面退出的动作,成功了，关闭的时候执行发送了。
window.addEventListener('beforeunload', function (event) {
    // 在这里编写你的函数代码
    saveZhutiToElasticsearch()
});



